#!/bin/bash

# 设置颜色变量
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # 恢复默认颜色

################## 实现通用action功能 ##################

success() {
  echo -en "\\033[60G[\\033[1;32m  OK  \\033[0;39m]\r"
  return 0
}

failure() {
  local rc=$?
  echo -en "\\033[60G[\\033[1;31mFAILED\\033[0;39m]\r"
  [ -x /Daili/plymouth ] && /Daili/plymouth --details
  return $rc
}

action() {
  local STRING rc

  STRING=$1
  echo -n "$STRING "
  shift
  "$@" && success $"$STRING" || failure $"$STRING"
  rc=$?
  echo
  return $rc
}

# 函数，判断命令是否正常执行
if_success() {
  local ReturnStatus=$3
  if [ $ReturnStatus -eq 0 ]; then
          action "$1" /bin/true
  else
          action "$2" /bin/false
          exit 1
  fi
}

################## 系统判断 ##################

if [ "$OSTYPE" == "linux-gnu" ]; then
    # Linux系统
    if [ -f /etc/os-release ]; then
        # 读取操作系统信息
        source /etc/os-release
        if [ $ID == "ubuntu" ] || [ $ID == "debian" ]; then
            echo -e "ubuntu"  
        elif [ $ID == "centos" ]; then
            # CentOS系统
            echo -e "Centos"
        else
            # 非Ubuntu、Debian或CentOS系统，抛出错误并停止脚本
            echo "不支持的操作系统: $ID"
            exit 1
        fi
    else
        # 无法确定具体Linux发行版，抛出错误并停止脚本
        echo "无法确定操作系统"
        exit 1
    fi
fi

################## 获取cpu架构和运行环境 ##################

function exitWithError {
    local errorMessage="$1"
    echo -e "\033[31m[ERROR] $errorMessage\033[0m" >&2
}

# Function to get CPU architecture
function get_cpu_arch {
    local commands=("$@")
    for cmd in "${commands[@]}"; do
        local CpuArch
        CpuArch=$(command -v $cmd >/dev/null && $cmd 2>/dev/null || type -p $cmd 2>/dev/null)
        if [[ -n "$CpuArch" ]]; then
            echo "$CpuArch"
            return
        fi
    done
}


if [[ -f "/etc/os-release" ]]; then
    . /etc/os-release
    case "$ID" in
        "ubuntu"|"debian"|"linuxmint")
            # Debian-based distributions
            CpuArch=$(get_cpu_arch "dpkg-architecture -qDEB_HOST_ARCH_CPU" "dpkg-architecture -qDEB_BUILD_ARCH_CPU" "uname -m")
            ;;
        "centos"|"fedora"|"rhel")
            # Red Hat-based distributions
            CpuArch=$(get_cpu_arch "uname -m" "arch" "uname")
            ;;
        *)
            # Unsupported Linux distribution
            CpuArch=$(get_cpu_arch "uname -m" "arch" "uname")
            if [[ -z "$CpuArch" ]]; then
                exitWithError "无法获取CPU体系结构"
            fi
            ;;
    esac
elif [[ -f "/etc/redhat-release" ]]; then
    # Older Red Hat-based distributions
    CpuArch=$(get_cpu_arch "uname -m" "arch" "uname")
else
    exitWithError "不支持的Linux发行版"
fi

#重新赋值
if [[ $CpuArch =~ "aarch64" ||  $CpuArch =~ "arm64" ]]; then
    cpu_Architecture="arm64"
elif [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
    cpu_Architecture="amd64"
fi

#获取版本
if awk '{print $2}' /etc/issue | grep -q -E 20.04; then
    version=20.04
elif awk '{print $2}' /etc/issue | grep -q -E 22.04; then
    version=22.04
elif awk '{print $2}' /etc/issue | grep -q -E 22.10; then
    version=22.10
else
    apt install -y chromium-browser || apt install -y chromium
fi


################# 主程序 ##################


OPTION=$(whiptail --title "脚本菜单" --menu "请选择一个" 15 60 7 \
"1" "打开Miao-Yunzai" \
"2" "启动Miao-Yunzai" \
"3" "前台启动Miao-Yunzai" \
"4" "重启Miao-Yunzai" \
"5" "重新配置BOT账号" \
"6" "报错修复" \
"7" "卸载Miao-Yunzai" 3>&1 1>&2 2>&3)

exitstatus=$?
if [ $exitstatus = 0 ]; then
    case $OPTION in
        1)
            #判断CPU架构
            if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
                #判断进程
                PID_NUM=`ps -ef | grep -i [m]iao-Yun | wc -l`
                #获取进程PID
                PID=`ps -ef | grep -i [m]iao-Yun | awk '{print $2}'`
                #如果进程存在则先删除进程，再启动
                if [ $PID_NUM -ne 0 ]; then
                    #尝试使用pm2打开
                    if ! pm2 log miao; then
                        echo -e "${RED}打开窗口失败${NC}"
                        exit 1
                    fi
                else
                    START=$(whiptail --title "Miao-Yunzai未启动" --menu "请选择一个" 15 60 4 \
                    "1" "前台启动(云服务器不推荐使用这个)" \
                    "2" "pm2后台启动(云服务器推荐这个)" 3>&1 1>&2 2>&3)
                    
                    exitstatus=$?
                    if [ $Exitstatus = 0 ]; then
                        if [ $START = 1 ]; then
                            cd && cd Miao-Yunzai
                            node app
                            exit 0
                        else
                            cd && cd Miao-Yunzai
                            pm2 start app.js --name="miao"
                            exit 0
                        fi
                    fi
                fi
            else
                echo "arm平台暂时不支持"
                exit 0
            fi
            ;;
        2)
            START=$(whiptail --title "Miao-Yunzai未启动" --menu "请选择一个" 15 60 4 \
            "1" "前台启动(手机使用这个)" \
            "2" "pm2后台启动(云服务器使用这个)" 3>&1 1>&2 2>&3)
            
            exitstatus=$?
            if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
                PID_NUM=`ps -ef | grep -i [m]iao-Yun | wc -l`
                PID=`ps -ef | grep -i [m]iao-Yun | awk '{print $2}'`
                if [ $exitstatus = 0 ]; then
                    #判断pm2进程                    
                    if [ $PID_NUM -ne 0 ]; then
                        pid=$(pm2 pid miao)
                        if [ ! -z $pid ]; then
                            pm2 stop miao
                        else
                            #如果为空说明不是通过pm2启动的
                            kill -9 $PID
                        fi
                    fi
                    
                    #重新判断
                    PID_NUM=`ps -ef | grep -i [m]iao-Yun | wc -l`
                    if [ $PID_NUM -eq 0 ]; then
                        #然后根据用户选择的启动方法重新启动
                        if [ $START -eq 1 ]; then
                            cd && cd Miao-Yunzai
                            node app || { echo -e "${RED}启动失败${NC}"; exit 1; }
                        else
                           cd && cd Miao-Yunzai
                           pm2 start app.js --name="miao"
                           echo -e "${YELLOW}启动成功，你可以使用 pm2 log miao 打开运行窗口${NC}"
                           exit 0
                        fi
                    fi
                else
                    bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh)
                    exit 0              
                fi
            else
                cd && cd Miao-Yunzai
                node app || { echo -e "${RED}启动失败${NC}"; exit 1; }
            fi
            ;;
        3)
            if (whiptail --title "注意前台启动不推荐使用在服务器上，应为断开SSH机器人也会掉线" --yesno "Choose between Yes and No." 10 60) then
                node app || { echo -e "${RED}启动失败${NC}"; exit 1; }
            else
                bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh)
                exit 0
            fi
            ;;
        4)
            if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
                PID_NUM=`ps -ef | grep -i [m]iao-Yun | wc -l`
                PID=`ps -ef | grep -i [m]iao-Yun | awk '{print $2}'`
                
                if [ $PID_NUM -eq 0 ]; then
                    echo -e "${YELLOW}有没有一种可能，我是说你都还没启动喵崽，我怎么进行重启${NC}"
                    sleep 3
                    bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh)
                    exit 0
                fi
                
                if [ $PID_NUM -ne 0 ]; then
                    pid=$(pm2 pid miao)
                    if [ ! -z $pid ]; then
                        pm2 restart miao
                        echo -e "${YELLOW}已重启${NC}"
                        bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh)
                        exit 0
                    else
                        kill -9 $PID
                        cd && cd Miao-Yunzai
                        node app || { echo -e "${RED}启动失败${NC}"; exit 1; }
                    fi
                fi
            else
                if [[ $CpuArch =~ "aarch64" || $CpuArch =~ "arm64"  ]]; then
                    echo -e "${RED}暂时不支持aarch64 和 arm64架构${NC}"
                    bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/admin.sh)
                    exit 0
                fi
            fi
            ;;
        5)
            #再次判断进程
            if [[ $CpuArch =~ "x86_64" || $CpuArch =~ "amd64"  ]]; then
                PID_NUM=`ps -ef | grep -i [m]iao-Yun | wc -l`
                PID=`ps -ef | grep -i [m]iao-Yun | awk '{print $2}'`
                
                pid=$(pm2 pid miao)
                if [ ! -z $pid ]; then
                    pm2 stop miao
                    cd && cd Miao-Yunzai && pnpm run login
                    exit 0
                else
                    kill -9 $PID
                    cd && cd Miao-Yunzai && pnpm run login
                    exit 0
                fi
            else
                cd && cd Miao-Yunzai && pnpm run login
                exit 0
            fi
            ;;
        6)
            #调用报错修复脚本
            exit 0
            ;;
        7)
            cd && rm -rf Miao-Yunzai
            echo -e "${YELLOW}好啦${NC}"
            exit 0
            ;;
        *)
            echo "输入错误，停止运行" && exit 1
            ;;
    esac

else
    bash <(curl -sL https://gitee.com/eulogyjiajia/miao_-script/raw/master/Script/install.sh)
    exit 0
fi